<template>
  <div :id="id"
       :style="chartStyle">
    <slot></slot>
  </div>
</template>
<script lang="ts">
import { Vue, Component, Watch, Prop } from "vue-property-decorator";
import echarts from "echarts";
@Component
export default class DdUserCharts extends Vue {
  myChart: any = null;
  // chart图表的总体样式 ，如宽 高 、background等
  @Prop({
    type: String,
    default: "width:600px;height:200px;"
  })
  chartStyle!: string;

  // echarts 所在的id
  @Prop({
    type: String,
    default() {
      let idStr = "";
      for (let i = 0; i < 6; i++) {
        let randomChar: string = String.fromCharCode(
          65 + Math.floor(Math.random() * 19) + i
        );
        idStr += randomChar;
      }
      return idStr;
    }
  })
  id!: string;

  // charts 配置
  @Prop({
    type: Object,
    required: true,
    default() {
      return {};
    }
  })
  option!: any;

  // 监听整体样式变化 重新加载
  @Watch("chartStyle")
  getChartStyle() {
    this.myChart.resize();
  }

  // 监听数据变化 更新图样式
  @Watch("option", { deep: true })
  getOption() {
    this.draw();
  }

  mounted() {
    this.$nextTick(() => {
      this.draw();
    });
  }

  draw() {
    if (document.getElementById(this.id)) {
      this.myChart =
        this.myChart == null
          ? echarts.init(document.getElementById(this.id))
          : this.myChart;
      this.myChart.setOption(this.option);
      // this.myChart.resize();
      var _this = this;
      window.addEventListener("resize", function() {
        _this.myChart.resize();
      });
    }
  }
}
</script>  